# -*- coding: utf-8 -*-
"""
    201901, Dr. Jie Zheng, Beijing & Xinglong, NAOC
    202101-? Dr. Jie Zheng & Dr./Prof. Linqiao Jiang
    Light_Curve_Pipeline
    v3 (2021A) Upgrade from former version, remove unused code
"""


import os
import numpy as np
import astropy.io.fits as fits
import astropy.io.ascii as ascii
from astropy import time, coordinates as coord, units as u
from .JZ_utils import loadlist, datestr, logfile, conf, meanclip, basefilename, unmatched, subset, sex2dec
from .JZ_plotting import plot_im_obj
from .J6_catalog import _catalog_


def catalog(ini_file, file_lst,
            offset_file,
            starxy,
            out_cat_fits,
            out_cat_table_txt,
            out_cat_list_txt,
            out_finding_img,
            # obj_coord=None,
            base_img_id=0,
            base_fits_file=None,
            red_path="",
            noplot=False,
            overwrite=False,
            log=None,
            extra_config=None):
    """
    Generate a big list of stars selected from times
    :param ini_file:
    :param file_lst:
    :param offset_file: offset file generated by Q4_offset
    :param starxy: a list of x,y of target/reference stars, [(x0,y0), (x1,y1), (x2,y2)....], or a n*2 array
    :param out_cat_fits: output file of fits table
    :param out_cat_table_txt: output file of text table (one row for one image, different stars on different columns)
    :param out_cat_list_txt: output file of text list (one row for one star, multiple rows for one image)
    :param out_finding_img: output file of finding chart
    :param obj_coord: ra/dec of image center, if None, then no jd->bjd, bjd=0
    :param base_img_id:
    :param base_fits_file: template image file, if base id == -1, this must be provided
    :param red_path:
    :param noplot:
    :param overwrite:
    :param log:
    :param extra_config:
    :return:
    """

    ini = conf(ini_file, extra_config)
    lf = logfile(log, level=ini["log_level"])

    if os.path.isfile(out_cat_fits) and not overwrite:
        lf.show("SKIP: " + out_cat_fits + "")
        return

    if not os.path.isfile(file_lst):
        lf.show("SKIP -- FILE NOT EXISTS: " + file_lst, logfile.ERROR)
        return

    # load list
    scif = loadlist(file_lst, suffix=ini["bf_mid"]+".fits", base_path=red_path,
                    separate_folder = ini["separate_folder"])

    catf = loadlist(file_lst, suffix=ini["cat_mid"]+".fits", base_path=red_path,
                    separate_folder=ini["separate_folder"])

    _catalog_(ini, scif, catf, offset_file, starxy,
              # obj_coord,
              base_img_id, base_fits_file,
              out_cat_fits, out_cat_table_txt, out_cat_list_txt, out_finding_img, noplot, lf)

    lf.close()